<script lang="ts" setup>
  import dayjs from 'dayjs';
  import { onMounted, ref } from 'vue';
  import useTable from '@/hooks/table';
  import { CmsArticleSearch, CmsArticle } from '@/types/cms';
  import { updateArticle, getArticleList, deleteArticle } from '@/api/cms';
  import { Message, Modal } from '@arco-design/web-vue';
  import { CmsArticleTypes } from '@/config/cms';
  import { useRouter } from 'vue-router';
  import SearchForm from './search-form.vue';
  import SimpleEditor from './editor/simple-editor.vue';
  import ExamEditor from './editor/exam/index.vue';

  const { pager, loading, total, list } = useTable<CmsArticle>();

  const router = useRouter();

  const searchParams = ref<Partial<CmsArticleSearch>>({});

  const getData = async () => {
    loading.value = true;
    try {
      const res = await getArticleList({
        ...pager.value,
        ...searchParams.value,
      });
      total.value = res?.data?.data?.total || 0;
      list.value = (res?.data?.data?.list || []).map((item) => {
        return {
          ...item,
          tagList: JSON.parse(item.tags || '[]') as string[],
        };
      });
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = (params: Partial<CmsArticleSearch>) => {
    pager.value.pageIndex = 1;
    searchParams.value = params;
    getData();
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  const simpleEditorConfig = ref<{
    visible: boolean;
    defaultContentType: number;
    article?: CmsArticle;
  }>({
    visible: false,
    defaultContentType: -1,
  });
  const handleSimpleEditorDone = (refresh: boolean) => {
    if (refresh) {
      getData();
    }
    simpleEditorConfig.value = {
      visible: false,
      defaultContentType: -1,
    };
  };
  const beginCreate = (contentType: number) => {
    if (contentType === 0) {
      window.open(
        router.resolve({
          name: 'CmsArticleEditorApp',
        }).href
      );
    } else {
      simpleEditorConfig.value = {
        visible: true,
        defaultContentType: contentType,
      };
    }
  };

  const beginEdit = (article: CmsArticle) => {
    if (article.contentType === 0) {
      window.open(
        router.resolve({
          name: 'CmsArticleEditorApp',
          query: {
            id: article.id,
          },
        }).href
      );
    } else {
      simpleEditorConfig.value = {
        visible: true,
        defaultContentType: article.contentType,
        article,
      };
    }
  };

  const examRecord = ref<CmsArticle | undefined>(undefined);
  const beginExam = (record: CmsArticle) => {
    if (record.contentType === 2) {
      Message.warning('公众号链接暂不支持答题送积分');
      return;
    }
    examRecord.value = record;
  };
  const handleExamDone = () => {
    examRecord.value = undefined;
  };

  const handleDelete = (article: CmsArticle) => {
    Modal.confirm({
      title: '确认删除？',
      content: '删除后无法恢复',
      async onBeforeOk() {
        await deleteArticle(article.id);
        getData();
      },
    });
  };

  const handleToggleState = async (article: CmsArticle) => {
    await updateArticle({
      id: article.id,
      state: article.state ? 0 : 1,
    });
    getData();
  };

  onMounted(() => {
    getData();
  });
</script>

<template>
  <div style="padding: 20px">
    <a-row :gutter="[20, 20]">
      <a-col>
        <a-card title="内容管理" :bordered="false">
          <template #extra>
            <a-dropdown>
              <a-button type="primary">
                <template #icon>
                  <icon-plus />
                </template>
                新建
              </a-button>
              <template #content>
                <a-doption
                  v-for="type in CmsArticleTypes"
                  :key="type.value"
                  @click="beginCreate(type.value)"
                >
                  {{ type.label }}
                </a-doption>
              </template>
            </a-dropdown>
          </template>

          <SearchForm @submit="handleSearch" />
        </a-card>
      </a-col>

      <a-col>
        <a-card :bordered="false">
          <a-table
            :bordered="{ cell: true }"
            :data="list"
            :loading="loading"
            :pagination="{
              total,
              current: pager.pageIndex,
              pageSize: pager.pageSize,
              showTotal: true,
              showJumper: true,
            }"
            @page-change="handlePageIndexChanged"
          >
            <template #columns>
              <a-table-column title="标题" data-index="articleTitle">
              </a-table-column>
              <a-table-column title="标签" data-index="tags">
                <template #cell="{ record }">
                  <a-space>
                    <a-tag
                      v-for="(tag, tagIndex) in record.tagList || []"
                      :key="tagIndex"
                    >
                      {{ tag }}
                    </a-tag>
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="作者" data-index="cmsAuthor.authorName" />
              <a-table-column title="栏目" data-index="cmsColumn.columnName" />
              <a-table-column title="类型" data-index="contentType">
                <template #cell="{ record }">
                  {{
                    CmsArticleTypes.find((i) => i.value === record.contentType)
                      ?.label
                  }}
                </template>
              </a-table-column>
              <a-table-column
                title="发布时间"
                data-index="publishTime"
                :width="180"
              >
                <template #cell="{ record }">
                  {{ dayjs(record.publishTime).format('YYYY/MM/DD HH:mm:ss') }}
                </template>
              </a-table-column>
              <a-table-column title="状态" data-index="gmtCreate" :width="100">
                <template #cell="{ record }">
                  <a-tag :color="record.state ? 'green' : 'blue'">
                    {{ record.state ? '已发布' : '草稿' }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="100" align="center">
                <template #cell="{ record }">
                  <a-dropdown>
                    <a-link>操作</a-link>
                    <template #content>
                      <a-doption @click="beginEdit(record)">编辑</a-doption>
                      <a-doption @click="beginExam(record)">设置答题</a-doption>
                      <a-doption @click="handleToggleState(record)">
                        {{ record.state ? '转到草稿箱' : '立即发布' }}
                      </a-doption>
                      <a-doption @click="handleDelete(record)">删除</a-doption>
                    </template>
                  </a-dropdown>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <SimpleEditor
      v-if="simpleEditorConfig.visible"
      :article="simpleEditorConfig.article"
      :default-content-type="simpleEditorConfig.defaultContentType"
      @close="handleSimpleEditorDone"
    />

    <ExamEditor
      v-if="examRecord"
      :article-id="examRecord.id"
      @close="handleExamDone"
    />
  </div>
</template>
